let user = localStorage.user && JSON.parse(localStorage.user)
console.log(user);

let passwordEl = document.querySelector('.password')
let newEmailEl = document.querySelector('.new_email')
let emailEl = document.querySelector('.email')

let saveBth = document.querySelector('.save')
//    用户名
let mingZi = document.querySelector('.mingzi')

saveBth.addEventListener('click', changePassword)


//   用户名获取
userName()
async function userName() {

    let res = await axios({
        methed: 'GET',
        url: '/api/user',
        params: {
            userId: user.userId,
        }
    })
    let html = ''
    html += `
                ${res.data.data.username} 
            `
    mingZi.innerHTML = html
}

async function changePassword(e) {

    let password = passwordEl.value.trim()
    let newEmail = newEmailEl.value.trim()
    let email = emailEl.value.trim()

    let emailReg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

    // 都为空的时候
    if (!password || !newEmail || !email) {
        return alert('请填入内容')
    }
    // // 新密码和确认密码不填时
    if (!emailReg.test(newEmail)) {
        return alert('请输入正确的QQ邮箱')
    }
    if (newEmail != email) {
        alert('两次邮箱设置不一样')
    }

    // 发请求，添加数据
    let res = await axios({
        method: 'POST',
        url: '/api/user/revise/email',
        data: {

            "userId": user.userId, //  以前的密码，找到账号
            "password": password, //  设置新邮箱
            'newemail': newEmail //  再次确认新邮箱

        }
    })
    console.log(res);


    let {
        code,
        msg,
        data
    } = res.data

    // 请求错误
    if (code) {
        return alert(msg)
    }
    // // 跳转页面至首页
    location.href = './set_message.html'

}